package com.banciyuan.wallpaper.config.retrofit;

import android.content.Context;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by squall on 2016/7/28.
 */
public class RetrofitFactory {

    private static Retrofit retrofit;

    private RetrofitFactory() {
    }

    public static Retrofit creatRetrofit(Context context) {
        if (retrofit == null) {
            File cacheFile = new File(context.getCacheDir().getAbsolutePath() + "/net_cache");
            OkHttpClient client = new OkHttpClient.Builder()
                    .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                    .cache(new Cache(cacheFile, 10 * 1024 * 1024))
                    .retryOnConnectionFailure(true)
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .build();


            retrofit = new Retrofit.Builder()
                    .baseUrl("http://api.bcy.net/api/")
//                    .baseUrl("http://llapi.bcy3.info/api/")
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();

        }
        return retrofit;
    }

    /**
     * Dangerous interceptor that rewrites the server's Cache-control header.
     */
    private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            int maxAge = 60; // read from Cache for 1 minute

            return originalResponse.newBuilder()
                    .addHeader("Cache-Control", "public, max-age=" + maxAge)
                    .build();
        }
    };
}
